import requests, pytest, os
import jsonpath
from commons.RequestUtil import RequestUtil
from commons.yaml_util import read_testcase
from commons.yaml_util import write_yaml
from commons.yaml_util import read_yaml
from commons.yaml_util import clear_yaml
from string import Template

dataList = {}  # 全局变量


class TestCase:

    @pytest.mark.parametrize("case_info", read_testcase("testcase/test_case.yaml"))
    def test_login_case(self, case_info):
        url = case_info['request']['url']
        if '$' in url:
            datas = read_yaml()
            url = Template(url).substitute(datas)
            print(f'我想看看：{url}')
        method = case_info['request']['method']
        data = case_info['request']['data']
        res = RequestUtil().request(method=method, url=url, params=data)
        print(f"响应结果：{res.text}")
        assert res.status_code == 200
        if 'extract' in case_info:
            for key, jsonpath_expr in case_info['extract'].items():
                valueList = jsonpath.jsonpath(res.json(), jsonpath_expr)
                dataList[key] = valueList[0]
                clear_yaml()
                write_yaml(dataList)


if __name__ == '__main__':
    pytest.main(['-s',  # 打印
                 '-v',  # 打印日志
                 '--capture=sys',  # 保留系统输出
                 'Test002.py',
                 '--clean-alluredir', '--alluredir=allure-results'])  # 存放测试结果
    os.system(r"allure generate -c -o 蜗牛测试报告")  # 生成html测试报告
    # 命令执行 python .\Test002.py
